package com.shulidata.mock.controller.ops;

import com.google.common.base.Strings;
import com.shulidata.mock.controller.BaseRestController;
import com.shulidata.mock.controller.base.NetProtocol;
import com.shulidata.mock.utils.Result;
import com.shulidata.mock.utils.SysCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 授权采集 - 数据源渠道列表页访问地址构建.
 *
 * @author fyduan
 * @date 16/7/29
 */
@RestController
public class AuthCollDataSourceListController extends BaseRestController {

    private static final String DEFAULT_PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA9XFbLjbf2KRxRup+P5BTDKQRwFZKi74iFiG/mnOQLPWrGj8Z5iVKFzFQMYTmxdYQ8b8y5fsK6RGa7ndHwUN6UQIDAQABAkBDKTKHEdLsyAqLGi1TnV1sTxTgaXxagrt3DOMOE2M3ObTZ+LL33zO2caTXLPnlHttfaFowQBpHIeyJcv09P6YBAiEA/AaCVbRxE/hwn31GuvVCPvdGZYC4Xehh0nzlB8CE1LECIQD5UEV0LDD0lkZyQIA4470OAKSMO/Uq1iv4Ez8Zui7noQIgcjho/XrH/OsN79qRIc5h9bOP/hS2eikFnKXqDvdbvCECIQDHF0oPZobFmwewjz+Vro+3kd3VOsAisBs2pK/8LIjuYQIhAI+U6i2yXFKtItvPHx33m03Cyo46WU2t8M9QJvEIm/J4";
    private static final String DEFAULT_PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALxNxMioerqB+imh/neTBrFwnXFw7yhiKoR0kADPuB/S411Xps8LclOW3bpn0amFtWq/abkJ1it1/Es8x3GKfwkCAwEAAQ==";

    @RequestMapping(method = RequestMethod.POST, value = "/ops/authcoll")
    public Result ctrlGetEncUrl(@RequestParam("hostname") String hostname,
                                @RequestParam("port") String port,
                                @RequestParam("path") String path,
                                @RequestParam("orgCode") String orgCode,
                                @RequestParam("dataSource") String dataSource,
                                @RequestParam("extraData") String extraData,
                                @RequestParam("privateKey") String privateKey) throws Exception {
        if (Strings.isNullOrEmpty(hostname) || Strings.isNullOrEmpty(path)
                || Strings.isNullOrEmpty(orgCode) || Strings.isNullOrEmpty(dataSource)
                || (Strings.isNullOrEmpty(port) || !NumberUtils.isNumber(port))) {
            return new Result(SysCode.ERR_PARAM, "参数错误");
        }

        AuthCollURLBuilder builder = new AuthCollURLBuilder(orgCode, Strings.isNullOrEmpty(privateKey)? DEFAULT_PRIVATE_KEY : privateKey, DEFAULT_PUBLIC_KEY);
        StringBuilder url = new StringBuilder(512)
                .append(NetProtocol.HTTP.getValue()).append(hostname)
                .append(":").append(port).append(path)
                .append("?p=").append(builder.enc(dataSource, extraData));

        // 参数加密
        return new Result(SysCode.OK, url.toString());
    }

}
